package models

import (
	"database/sql"
	"time"
)

type PromiseModel struct {
	Id		int64`db:"id"`
	Name	string`db:"name"`
	Path    string`db:"path"`
	Value	uint8`db:"value"`
	CreateAt int64  `db:"create_at"`
	UpdateAt int64  `db:"update_at"`
}

func CreatePromise(db *sql.DB, name, path string, value uint8) (bool, error) {
	sqlStr := "INSERT INTO `u_promises` (`name`,`path`,`value`,`create_at`,`update_at`) Values (?,?,?,?,?)"
	stmt,err := db.Prepare(sqlStr)
	if err != nil {
		return false, err
	}
	now := time.Now().Unix()
	res,err := stmt.Exec(name,path,value,now,now)
	if err != nil {
		return false,err
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false,err
	}
	return rows == 1,nil
}

func DelPromise(db *sql.DB,id int64) (bool,error) {
	sqlStr := "DELETE FROM `u_promises` WHERE `id` = ?"
	stmt,err := db.Prepare(sqlStr)
	if err != nil {
		return false,err
	}
	res,err := stmt.Exec(id)
	if err != nil {
		return false,err
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false,err
	}
	return rows == 1,nil
}

func UpdatePromisePath(db *sql.DB, id int64, path string) (bool, error) {
	sqlStr := "UPDATE `u_promises` SET `path` = ? WHERE `id` = ?"
	stmt,err := db.Prepare(sqlStr)
	if err != nil {
		return false,err
	}
	res,err := stmt.Exec(path,id)
	if err != nil {
		return false, nil
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false, nil
	}
	return rows == 1, nil
}

func UpdatePromiseValue(db *sql.DB, id int64, value uint8) (bool, error) {
	sqlStr := "UPDATE `u_promises` SET `value` = ? WHERE `id` = ?"
	stmt,err := db.Prepare(sqlStr)
	if err != nil {
		return false,err
	}
	res,err := stmt.Exec(value,id)
	if err != nil {
		return false, nil
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false, nil
	}
	return rows == 1, nil
}


func UpdatePromise(db *sql.DB, id int64,path string, value uint8) (bool, error) {
	sqlStr := "UPDATE `u_promises` SET `path` = ?,`value` = ? WHERE `id` = ?"
	stmt,err := db.Prepare(sqlStr)
	if err != nil {
		return false,err
	}
	res,err := stmt.Exec(path,value,id)
	if err != nil {
		return false, nil
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false, nil
	}
	return rows == 1, nil
}